import React from 'react';
import { View, CameraRoll, Text, ScrollView, Image, PermissionsAndroid } from 'react-native';
import styles from './styles';

async function requestCameraPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera")
      return true;
    } else {
      console.log("Camera permission denied")
    }
  } catch (err) {
    console.warn(err)
  }
  return false;
}
class Images extends React.Component {
  static navigationOptions = {
    title: '图库操作',
    text: '',
  };
  state = {
    photos:[],
    tip: undefined,
  }
  componentWillMount() {
    this.fetchParam = { first: 50};
    requestCameraPermission().then(
      () => {
        CameraRoll.getPhotos(this.fetchParam).then((data) => {
          this.state.tip = '正在获取图片';
          this.getPhotoResults(data);
        }).catch(err=> {
          this.state.tip = '获取图片失败！';
          console.log(err);
        });
      }
    ).catch(err => {
      this.state.tip = '未获取到访问相册(外部存储）的权限！';
      console.log(err);
    });
    // const perm = requestCameraPermission();
    // if (!perm) {
    //   this.state.tip = '未获取到访问相册(外部存储）的权限!';
    // }
    // CameraRoll.getPhotos(this.fetchParam).then((data) => {
    //   this.state.tip = '正在获取图片';
    //   this.getPhotoResults(data);
    // }).catch(err=> {
    //   this.state.tip = '获取图片失败！';
    //   console.log(err);
    // });
  }

  getPhotoResults = (data) => {
    const assets = data.edges.map(item=>item.node);
    if (!data.page_info.has_next_page) {
      console.log('图片已经全部获取');
      // Alert.alert(
      //   '操作结果',
      //   '图片已经全部获取'
      // );
      // return;
    }
    this.setState({ photos: data.edges, tip: data.edges.length > 0 ? undefined : '未获取到图片' });
    // this.fetchParam = { first: 50, after: data.page_info.end_cursor };
    // console.log('获取下一组图片');
    // CameraRoll.getPhotos(this.fetchParam).then((data) => {
    //   this.getPhotoResults(data);
    // }).catch(rr=> {
    //   console.log(err);
    // });
  }
  render() {
    return (
      <View style={styles.container}>
        {
          this.state.tip && (
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
              <View><Text>{!this.state.photos || this.state.photos.length === 0 ? '没有图片' : ''}</Text></View>
            </View>
          )
        }
        { !this.state.tip && (
        <ScrollView>
          {this.state.photos.map((p, i) => {
            return (
              <Image
                key={i}
                style={{
                  width: 300,
                  height: 100,
                  margin: 10,
                }}
                source={{ uri: p.node.image.uri }}
              />
            );
          })}
        </ScrollView>
      )}
      </View>
    )
  }
}

export default Images;
